package com.shaw.mybatisx.executor;

import com.shaw.mybatisx.session.Configuration;
import com.shaw.mybatisx.executor.parameter.ParameterHandler;
import com.shaw.mybatisx.executor.result.ResultSetHandler;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2018/4/1.
 */
public class SimpleExecutor implements Executor {

    private ParameterHandler parameterHandler;
    private ResultSetHandler resultSetHandler;

    public SimpleExecutor(){
        init(new ParameterHandler(),new ResultSetHandler());
    }

    public SimpleExecutor(ParameterHandler parameterHandler){
        init(parameterHandler,new ResultSetHandler());
    }

    public SimpleExecutor(ResultSetHandler resultSetHandler){
        init(new ParameterHandler(),resultSetHandler);
    }

    public SimpleExecutor(ParameterHandler parameterHandler,ResultSetHandler resultSetHandler){
        init(parameterHandler,resultSetHandler);
    }

    private void init(ParameterHandler parameterHandler,ResultSetHandler resultSetHandler){
        this.parameterHandler = parameterHandler;
        this.resultSetHandler = resultSetHandler;
    }

    @Override
    public <E> List<E> query(Configuration.MapperDate mapperDate, Object parameter) {
        List<E> list = new ArrayList<E>();
        try {
            PreparedStatement ps = SimpleExecutor.getConnection().prepareStatement(this.parameterHandler.handlerParameterSet(mapperDate.getSql(),parameter));
            ps.execute();
            ResultSet rs = ps.getResultSet();
            list  = resultSetHandler.handlerResultSet(rs,mapperDate.getType());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC";
        String username ="root";
        String password = "root";
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(url,username,password);

    }

}
